package com.umeox.watch.moto.launcher.ui;

import android.animation.ValueAnimator;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeox.moto.common.utils.HeartRateControl;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.widget.ProgressView;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.interfaces.IPullApiClient;
import com.umeox.watch.moto.dataservice.proxy.PullApiClientProxy;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.ui.view.CustomClipLoading;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


public class HeartRateDetectActivity extends ThemeAppCompatActivity {

    private static final String TAG = "HeartRateActivity";
    public static final int COUNT_TIME_TOTAL = 30;
    public static final int MILLIS_IN_FUTURE = 10000;
    public static final int INVALID_COUNT_MAX = 2;
    private TextView mCurrentHeartRateTv;
    private ProgressView mProgressView;
    private View mWearErrorView;
    private View mInitView;
    private ImageView mRedetectAb;

    private CustomClipLoading mCustomClipLoading;

    private List<Integer> mHeartRateValues = new ArrayList<>();
    private ValueAnimator mIncreaseAnimator;
    private int mInvalidCount;

    private Disposable mDisposable;
    public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("000");


    private IPullApiClient pullApiClient;
    private long startTime;
    private long endTime;

    private final CountDownTimer mDownTimer = new CountDownTimer(MILLIS_IN_FUTURE, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            mCustomClipLoading.stop();
            mInitView.setVisibility(View.GONE);
            startDetectHeartRate();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_heart_rate_detect);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        initView();
        initData();
    }


    private void initView() {
        mProgressView = findViewById(R.id.pvCountdown);
        mCurrentHeartRateTv = findViewById(R.id.tv_heart_rate);
        mWearErrorView = findViewById(R.id.wear_error_ll);
        mRedetectAb = findViewById(R.id.redetect_ab);


        mCustomClipLoading = findViewById(R.id.loading_view);
        mInitView = findViewById(R.id.init_ll);
        mDownTimer.start();
        mInitView.setVisibility(View.VISIBLE);
        mCustomClipLoading.start();

    }

    private void initData() {
        HeartRateControl.openRate();
        mRedetectAb.setOnClickListener(v -> restartDetect());
    }

    private final Observer<Long> mObserver = new Observer<Long>() {

        @Override
        public void onSubscribe(Disposable d) {
            //UToast.show("onSubscribe", Toast.LENGTH_SHORT);
            mDisposable = d;
            mIncreaseAnimator.start();
        }

        @Override
        public void onNext(Long aLong) {
            final String value = HeartRateControl.getRateValue();
            final String hrValue = TextUtils.isEmpty(value) ? "0" : value;
            final int rateValue = Integer.parseInt(hrValue, 16);
            if (rateValue != 0) {
                mInvalidCount = 0;
                mHeartRateValues.add(rateValue);
            } else {
                mInvalidCount++;
            }
            if (mInvalidCount >= INVALID_COUNT_MAX) {
                mInvalidCount = 0;
                mIncreaseAnimator.removeAllUpdateListeners();
                mProgressView.setProgress(0);
                mDisposable.dispose();
                HeartRateControl.closeRate();
                //显示正确佩戴的UI
                mWearErrorView.setVisibility(View.VISIBLE);
            }
            mCurrentHeartRateTv.setText(rateValue >= 100 ? DECIMAL_FORMAT.format(rateValue) : String.valueOf(rateValue));
        }

        @Override
        public void onError(Throwable e) {
            Log.e(TAG, "onError: ", e);
        }

        @Override
        public void onComplete() {
            HeartRateControl.closeRate();
            if (mHeartRateValues.isEmpty()) {
                return;
            }
            endTime = System.currentTimeMillis();
            final Integer max = Collections.max(mHeartRateValues);
            final Integer min = Collections.min(mHeartRateValues);
            final int averageValue = getAverageValue();
            ContentValues contentValues = new ContentValues();
            contentValues.put(DataProvider.HeartRateProvider.MIN_VALUE, min);
            contentValues.put(DataProvider.HeartRateProvider.MAX_VALUE, max);
            contentValues.put(DataProvider.HeartRateProvider.AVERAGE_VALUE, averageValue);
            contentValues.put(DataProvider.HeartRateProvider.MEASURE_TIME, endTime);
            DataProvider.saveHeartRate(contentValues);

            uploadHeartRate("1#0", startTime, endTime, averageValue, min, max);

            //返回结果
            Intent intent = new Intent();
            intent.putExtra("data", new int[]{min, max, averageValue});
            HeartRateDetectActivity.this.setResult(RESULT_OK, intent);
            finish();

        }
    };

    private void uploadHeartRate(String code, long startTime, long endTime, int averageValue, Integer min, Integer max) {
        if (pullApiClient == null) {
            pullApiClient = PullApiClientProxy.fetchBinder();
        }
        try {
            pullApiClient.uploadHeartRate(code, startTime, endTime, averageValue, min, max);
        } catch (Exception e) {
            Log.w(TAG, "上传心率数据失败 : ", e);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        HeartRateControl.closeRate();
        mDownTimer.cancel();
        if (mIncreaseAnimator != null) {
            mIncreaseAnimator.cancel();
        }
    }

    private void restartDetect() {
        mWearErrorView.setVisibility(View.GONE);
        HeartRateControl.openRate();
        mDownTimer.start();
        mInitView.setVisibility(View.VISIBLE);
        mCustomClipLoading.start();
    }

    private void startDetectHeartRate() {
        //UToast.show("startDetectHeartRate", Toast.LENGTH_SHORT);
        mHeartRateValues.clear();
        mProgressView.setProgress(0);
        mIncreaseAnimator = ValueAnimator.ofFloat(0, 1).setDuration(TimeUnit.SECONDS.toMillis(COUNT_TIME_TOTAL));
        mIncreaseAnimator.setInterpolator(new LinearInterpolator());
        mIncreaseAnimator.addUpdateListener(animation -> {
            float progress = (float) animation.getAnimatedValue();
            mProgressView.setProgress(progress);
        });

        Observable
                .interval(1, TimeUnit.SECONDS).take(COUNT_TIME_TOTAL)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mObserver);

        startTime = System.currentTimeMillis();

    }


    private int getAverageValue() {
        int sum = 0;
        for (Integer heartRateValue : mHeartRateValues) {
            sum = sum + heartRateValue;
        }
        return sum / mHeartRateValues.size();
    }
}
